package com.zkzx.company.api.controller.truck;

import com.alibaba.fastjson.JSON;
import com.zkzx.common.company.model.CompanyVO;
import com.zkzx.common.exception.BaseException;
import com.zkzx.common.exception.ExceptionEnum;
import com.zkzx.common.global.Global;
import com.zkzx.common.sms.constants.SmsTemplateEnum;
import com.zkzx.common.truck.command.TruckCommand;
import com.zkzx.common.truck.constants.TruckStatusEnum;
import com.zkzx.common.truck.model.CompanyTruckVO;
import com.zkzx.common.truck.model.TruckListVO;
import com.zkzx.common.truck.model.TruckVO;
import com.zkzx.common.truck.param.TruckFilterParam;
import com.zkzx.common.vo.PageResult;
import com.zkzx.common.vo.RequestFilterParams;
import com.zkzx.common.vo.StatusVO;
import com.zkzx.company.api.client.company.CompanyClient;
import com.zkzx.company.api.client.truck.TruckClient;
import com.zkzx.company.api.controller.BaseController;
import com.zkzx.util.json.JSONResultUtil;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 北京中科智兴物联科技有限公司 @版权所有
 *
 * @Author: zhaoyihe@zkraising.com
 * @Date: 2021/05/12/0:20
 * @Description:
 */
@RestController
@Validated
@Slf4j
@Api(tags="车辆管理")
@RequestMapping(value = "/trucks")
public class TruckController extends BaseController {

    @Autowired
    private TruckClient truckClient;

    @Autowired
    private CompanyClient companyClient;

    @GetMapping
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "获取车辆列表", notes = "获取车辆列表")
    public PageResult<TruckListVO> find(@ApiParam(value = "查询参数") TruckFilterParam filterParam,
                                        @ApiParam(value = "分页查询参数") RequestFilterParams params) {

        PageResult<TruckListVO> result = companyClient.
                findTruckList(JSONResultUtil.object2JSON(filterParam), JSONResultUtil.object2JSON(params), getCompanyId());

        if(CollectionUtils.isEmpty(result.getResult())){
            return new PageResult<>(params.getPage(),params.getPerPage(),null, Global.ZERO);
        }

        List<TruckListVO> truckListVOS = new ArrayList<>();
        for (TruckListVO truckListVO : result.getResult()) {
            TruckVO truckVO = truckClient.getById(truckListVO.getId(),getCompanyId(),super.getUserId());
            truckListVO.setCid(truckVO.getCid());
            truckListVO.setLastModifiedTime(truckVO.getLastModifiedTime());
            truckListVO.setRelationNumber(truckVO.getRelationNumber());
            truckListVO.setTruckSourceVO(truckVO.getTruckSourceVO());
            truckListVO.setLastModifiedTime(truckVO.getLastModifiedTime());
            truckListVO.setStatus(truckVO.getStatusVO());
            truckListVOS.add(truckListVO);
        }

        return new PageResult<>(params.getPage(), params.getPerPage(), truckListVOS, result.getTotalNum());
    }


    @GetMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "获取车辆详细", notes = "获取车辆详细")
    public TruckVO getById(@PathVariable("id") Integer id){
        return truckClient.getById(id,getCompanyId(),super.getUserId());
    }


    @PutMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "修改车辆信息", notes = "修改车辆信息")
    public void update(@PathVariable("id") Integer id, @RequestBody @Valid TruckCommand command){

        // 更新关联关系数据
        command.setId(id);
        truckClient.update(id,command,super.getUserId());
        companyClient.updateTruck(command,super.getCompanyId());
    }


    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    @ApiOperation(value = "新增车辆信息", notes = "新增车辆信息")
    public StatusVO add(@RequestBody @Valid TruckCommand command) {
        CompanyVO companyVO = companyClient.getById(super.getCompanyId());
        if(StringUtils.isEmpty(companyVO.getThreeId())){
            throw new BaseException(ExceptionEnum.COMPANY_MEMBER_REVIEW_ERROR.getCode(),ExceptionEnum.COMPANY_MEMBER_REVIEW_ERROR.getMsg());
        }

        command.setCompanyId(super.getCompanyId());
        StatusVO statusVO = truckClient.add(command,super.getUserId());

        // 需要进行重新查询  因为网货有可能存在 进行更新中间表的信息 保持数据一致
        TruckVO truckVO = this.getById(statusVO.getId());
        // 更新关联关系
        command.setId(statusVO.getId());
        command.setStatus(statusVO.getValue());
        command.setSource(truckVO.getTruckSourceVO().getName());
        command.setType(truckVO.getTypeVO().getName());
        companyClient.updateTruck(command,super.getCompanyId());

        //如果网货存已审核通过，且同步到收单系统，则发短信通知
        if (TruckStatusEnum.VERIFY_SUCCESS.name().equals(statusVO.getValue()) || TruckStatusEnum.APPROVE_FAIL.name().equals(statusVO.getValue())){
            this.sendTruckSms(statusVO.getValue(),companyVO.getMemberMobile(),companyVO.getName(),truckVO.getHeaderLicenseVO().getLicence());
        }

        return statusVO;
    }

    @PostMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "提交", notes = "提交")
    public StatusVO verification(@PathVariable("id") Integer id ) {
        CompanyVO companyVO = companyClient.getById(super.getCompanyId());
        StatusVO statusVO = truckClient.verification(id, companyVO.getThreeId(), super.getCompanyId(), super.getUserId());
        TruckCommand command = new TruckCommand();
        command.setCompanyId(super.getCompanyId());
        command.setId(statusVO.getId());
        command.setStatus(statusVO.getValue());
        companyClient.updateTruck(command,super.getCompanyId());

        //如果网货存已审核通过，且同步到收单系统，则发短信通知
        if (TruckStatusEnum.VERIFY_SUCCESS.name().equals(statusVO.getValue()) || TruckStatusEnum.APPROVE_FAIL.name().equals(statusVO.getValue())){
            //查询车辆信息
            TruckVO truckVO = truckClient.getById(id, super.getCompanyId(), super.getUserId());
            this.sendTruckSms(statusVO.getValue(),companyVO.getMemberMobile(),companyVO.getName(),truckVO.getHeaderLicenseVO().getLicence());
        }

        return statusVO;
    }

    @GetMapping("/list")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "获取车辆下拉列表", notes = "获取车辆下拉列表")
    public List<CompanyTruckVO> findAll(){
        return companyClient.getByTruckIdCompanyId(Global.ZERO,super.getCompanyId());
    }

    /**
     * 车辆审核短信通知
     * @param status  车辆状态
     * @param mobile 公司联系人手机号
     * @param companyName 公司名称
     * @param LicensePlate 车牌号
     */
    public void sendTruckSms(String status,String mobile,String companyName,String LicensePlate){
        Map<String, String> parameterMap = new HashMap<>();
        //审核成功和审核失败传参一致
        parameterMap.put(SmsTemplateEnum.TRUCK_EXAMINE_SUCCESS.getParameterArr()[Global.ZERO],companyName);
        parameterMap.put(SmsTemplateEnum.TRUCK_EXAMINE_SUCCESS.getParameterArr()[Global.ONE],LicensePlate);
        if (TruckStatusEnum.VERIFY_SUCCESS.name().equals(status)){
            //已验证
            companyClient.sendSms(mobile, SmsTemplateEnum.TRUCK_EXAMINE_SUCCESS.getTemplate(), JSON.toJSONString(parameterMap));
        }else if (TruckStatusEnum.APPROVE_FAIL.name().equals(status)){
            //审核驳回
            companyClient.sendSms(mobile, SmsTemplateEnum.TRUCK_EXAMINE_FAIL.getTemplate(), JSON.toJSONString(parameterMap));
        }
    }

}
